<?php

namespace app\admin\model\xmwms;

use think\Model;

/**
 * Warehouse
 */
class Warehouse extends Model
{
    // 表名
    protected $name = 'wms_warehouse';

    /**
     * @var string 自动写入时间戳字段
     */
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'city_text',
    ];

    // 字段类型转换
    protected $type = [
        'deletetime' => 'timestamp:Y-m-d H:i:s',
    ];

    protected static function onAfterInsert($model)
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
        }
    }

    public function getCityAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setCityAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getCityTextAttr($value, $row): string
    {
        if (isset($row['city'])) {
            if ($row['city'] === '' || $row['city'] === null) return '';
            $cityNames = \think\facade\Db::name('area')->whereIn('id', $row['city'])->column('name');
            return $cityNames ? implode(',', $cityNames) : '';
        } else {
            return '';
        }
    }
}